const mongoose = require('mongoose');
const {env} = require('../config');
const O = require('../utils/O');
// const common = require('../utils/common');
// const { logger } = require('../utils/logger');
const fs = require('fs');

let mongo_replica = env.MONGO.REPLICA;
let mongo_ssl_ca_path = env.MONGO.SSL_CA_PATH;
let mongo_read_preference = env.MONGO.READ_PREFERENCE;
let mongo_retry_writes = env.MONGO.RETRY_WRITES;

let url = 'mongodb://' + env.MONGO.USER + ':' +  env.MONGO.PASS +  '@' +  env.MONGO.HOST
          +  ':' +  env.MONGO.PROT +  '/' +  env.MONGO.DB;
let url_option = '';
mongo_replica = O.isStringEmp(mongo_replica) ? '' : `replicaSet=${mongo_replica}`;
mongo_read_preference = O.isStringEmp(mongo_read_preference) ? ''  : `readPreference=${mongo_read_preference}`;
mongo_retry_writes = O.isStringEmp(mongo_retry_writes)  ? ''  : `retryWrites=${mongo_retry_writes}`;
if (mongo_ssl_ca_path) {
  url_option += '&' + 'ssl=true';
}
if (mongo_replica) {
  url_option += '&' + mongo_replica;
}
if (mongo_read_preference) {
  url_option += '&' + mongo_read_preference;
}
if (mongo_retry_writes) {
  url_option += '&' + mongo_retry_writes;
}
if (url_option) {
  url = url + '?' + url_option.substr(1);
}

let option = {};
if (mongo_ssl_ca_path) {
  const certFileBuf = [fs.readFileSync(mongo_ssl_ca_path)];
  option = {
    sslValidate: true,
    sslCA: certFileBuf,
    useNewUrlParser: true,
    useFindAndModify: false,
    useCreateIndex: true,
    useUnifiedTopology: true,
  };
}

// Mongoose for local env
if (env.ENV == 'dev' || env.ENV == 'local') {
  let mongodb_uri = 'mongodb://localhost:27017/test';
  // let mongodb_uri = 'mongodb+srv://test:A6de3rYrPKdatGTm@test-egift.7j6hv.mongodb.net/test?retryWrites=true&w=majority';
  mongoose
    .connect(mongodb_uri, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
      useFindAndModify: false,
      useCreateIndex: true,
    })
    .then(() => console.log('Connected to MongoDB...'))
    .catch((err) => console.error('Could not connect to MongoDB... ', err));
} else {
  //Mongoose - only ssl
  mongoose
    .connect(url, option)
    .then(() => console.log('Mongoose Connected to MongoDB...'))
    .catch((err) => console.error('Could not connect to MongoDB... ', err));
}

// MongoClient - SSL or TLS;
// let client = MongoClient.connect(
//     url,
//     {
//         tlsCAFile: `rds-combined-ca-bundle.pem`,
//         // sslValidate: true,
//         // sslCA: certFileBuf,
//         // useNewUrlParser: true,
//     },
//     function (err, client) {
//         if (err) {
//             console.log('aws document db connection fail');
//             console.log(err);
//         } else {
//             console.log('aws document db connection success');
//         }
//     }
// );

const schema = new mongoose.Schema({
  user: String,
  name: String,
});

const mongodb = {
  createUser: async (data) => {
    const User = mongoose.model('User', schema);
    const user = new User(data);
    try {
      await user.save();
    } catch (err) {

    }
  },
};

module.exports = mongodb;
